package com.dianneng.show.fragment;


import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.dianneng.show.R;
import com.dianneng.show.base.BaseFragment;
import com.dianneng.show.http.RetrofitHelper;
import com.dianneng.show.model.BaseResult;
import com.dianneng.show.model.DeviceListInfo;
import com.dianneng.show.model.LastLightDataInfo;
import com.dianneng.show.model.ProjectListInfo;
import com.dianneng.show.util.ACache;
import com.dianneng.show.util.CommandUtil;
import com.dianneng.show.util.Constant;
import com.dianneng.show.widget.ItemLayout;
import com.xingliuhua.libnetstatelayout.view.INetErrorView;
import com.xingliuhua.libnetstatelayout.view.NetStateLayout;
import com.xw.repo.BubbleSeekBar;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class StateFragment extends BaseFragment {

    @BindView(R.id.rb_qing)
    RadioButton rbQing;
    @BindView(R.id.rb_yin)
    RadioButton rbYin;
    @BindView(R.id.rb_bang)
    RadioButton rbBang;
    @BindView(R.id.rb_ye)
    RadioButton rbYe;
    @BindView(R.id.rb_zi)
    RadioButton rbZi;
    @BindView(R.id.rg_total)
    RadioGroup rgTotal;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_kwh)
    TextView tvKwh;
    @BindView(R.id.il_name)
    ItemLayout ilName;
    @BindView(R.id.il_shen)
    ItemLayout ilShen;
    @BindView(R.id.il_shi)
    ItemLayout ilShi;
    @BindView(R.id.il_qu)
    ItemLayout ilQu;
    @BindView(R.id.il_weizhi)
    ItemLayout ilWeizhi;
    @BindView(R.id.il_sn)
    ItemLayout ilSn;
    @BindView(R.id.il_wangguan)
    ItemLayout ilWangguan;
    @BindView(R.id.il_snweizhi)
    ItemLayout ilSnweizhi;
    @BindView(R.id.il_date)
    ItemLayout ilDate;
    @BindView(R.id.bs_yuzhi)
    BubbleSeekBar bsYuzhi;
    @BindView(R.id.bs_yanshi)
    BubbleSeekBar bsYanshi;
    @BindView(R.id.rb_changliang)
    RadioButton rbChangliang;
    @BindView(R.id.bs_changliang)
    BubbleSeekBar bsChangliang;
    @BindView(R.id.iv_changliang_cover)
    ImageView ivChangliangCover;
    @BindView(R.id.rb_jieneng)
    RadioButton rbJieneng;
    @BindView(R.id.btn_ying)
    Button btnYing;
    @BindView(R.id.btn_ruan)
    Button btnRuan;
    @BindView(R.id.bs_gaoliang)
    BubbleSeekBar bsGaoliang;
    @BindView(R.id.bs_jieneng)
    BubbleSeekBar bsJieneng;
    @BindView(R.id.bs_jianliang)
    BubbleSeekBar bsJianliang;
    @BindView(R.id.bs_gaoliang_chang)
    BubbleSeekBar bsGaoliangChang;
    @BindView(R.id.bs_jianan)
    BubbleSeekBar bsJianan;
    @BindView(R.id.iv_jieneng_cover)
    ImageView ivJienengCover;
    @BindView(R.id.nt_total)
    NetStateLayout ntTotal;
    @BindView(R.id.iv_kongzhi_cover)
    ImageView ivKongzhiCover;

    boolean isYingjian=false;

    ZiDingYiData ziDingYiData=new ZiDingYiData();

    @Override
    protected int setLayoutResourceID() {
        return R.layout.fragment_state;
    }

    @Override
    protected void setUpView() {
        ntTotal.setContentState(NetStateLayout.CONTENT_STATE_HIDE);
        ntTotal.setOnRetryClickListener(new INetErrorView.OnRetryClickListener() {
            @Override
            public void onRetryClicked() {
                ntTotal.setContentState(NetStateLayout.CONTENT_STATE_SHOW_LOADING);
                projectlist();
            }
        });
        rgTotal.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_qing://晴天
//                        bsYuzhi.setProgress(90);//照度阈值
//                        bsYanshi.setProgress(9);//高亮延时
                        bsGaoliang.setProgress(70);//高亮亮度
                        bsJieneng.setProgress(10);//节能亮度
                        bsJianliang.setProgress(5);//渐亮时长
                        bsGaoliangChang.setProgress(10);//高亮时长
                        bsJianan.setProgress(5);//渐暗时长
                        break;
                    case R.id.rb_yin://阴天
//                        bsYuzhi.setProgress(80);//照度阈值
//                        bsYanshi.setProgress(8);//高亮延时
                        bsGaoliang.setProgress(80);//高亮亮度
                        bsJieneng.setProgress(20);//节能亮度
                        bsJianliang.setProgress(3);//渐亮时长
                        bsGaoliangChang.setProgress(20);//高亮时长
                        bsJianan.setProgress(10);//渐暗时长
                        break;
                    case R.id.rb_bang://傍晚
//                        bsYuzhi.setProgress(70);//照度阈值
//                        bsYanshi.setProgress(7);//高亮延时
                        bsGaoliang.setProgress(90);//高亮亮度
                        bsJieneng.setProgress(20);//节能亮度
                        bsJianliang.setProgress(3);//渐亮时长
                        bsGaoliangChang.setProgress(20);//高亮时长
                        bsJianan.setProgress(15);//渐暗时长
                        break;
                    case R.id.rb_ye://夜间
//                        bsYuzhi.setProgress(60);//照度阈值
//                        bsYanshi.setProgress(6);//高亮延时
                        bsGaoliang.setProgress(100);//高亮亮度
                        bsJieneng.setProgress(10);//节能亮度
                        bsJianliang.setProgress(5);//渐亮时长
                        bsGaoliangChang.setProgress(10);//高亮时长
                        bsJianan.setProgress(10);//渐暗时长
                        break;
                    case R.id.rb_zi://自定义
//                        bsYuzhi.setProgress(50);//照度阈值
//                        bsYanshi.setProgress(5);//高亮延时
                        bsGaoliang.setProgress(ziDingYiData.gaoliang);//高亮亮度
                        bsJieneng.setProgress(ziDingYiData.jieneng);//节能亮度
                        bsJianliang.setProgress(ziDingYiData.jianliang);//渐亮时长
                        bsGaoliangChang.setProgress(ziDingYiData.gaoliangchang);//高亮时长
                        bsJianan.setProgress(ziDingYiData.jianan);//渐暗时长
                        break;
                }
            }
        });
        rgTotal.check(rbQing.getId());
        rbChangliang.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ivJienengCover.setVisibility(View.VISIBLE);
                    ivKongzhiCover.setVisibility(View.VISIBLE);
                    ivChangliangCover.setVisibility(View.GONE);
                    rbJieneng.setChecked(false);
                }
            }
        });
        rbJieneng.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (isYingjian)
                        ivJienengCover.setVisibility(View.VISIBLE);
                    else
                        ivJienengCover.setVisibility(View.GONE);
                    ivKongzhiCover.setVisibility(View.GONE);
                    ivChangliangCover.setVisibility(View.VISIBLE);
                    rbChangliang.setChecked(false);
                }
            }
        });
        rbJieneng.setChecked(true);
    }

    @Override
    protected void setUpData() {
        background();
    }

    private void bindData() {
        tvDate.setText(ACache.get(Utils.getApp()).getAsString(Constant.TIME));
        float eq = Float.valueOf(ACache.get(Utils.getApp()).getAsString(Constant.EQ)) / 100f;
        tvKwh.setText(eq + "kW·h");

        ilName.setRightText(ACache.get(Utils.getApp()).getAsString(Constant.NAME));
        String address=ACache.get(Utils.getApp()).getAsString(Constant.ADDRESS);
        if (TextUtils.isEmpty(address) || address.split("，").length<4){
            ilShen.setRightText("江苏省");
            ilShi.setRightText("无锡市");
            ilQu.setRightText("新吴区");
            ilWeizhi.setRightText("展示大厅");
        }else {
            String[] aaa=address.split("，");
            ilShen.setRightText(aaa[0]);
            ilShi.setRightText(aaa[1]);
            ilQu.setRightText(aaa[2]);
            ilWeizhi.setRightText(aaa[3]);
        }
        ilSn.setRightText(ACache.get(Utils.getApp()).getAsString(Constant.SN));
        ilWangguan.setRightText(ACache.get(Utils.getApp()).getAsString(Constant.DEVICE_SN));
        ilSnweizhi.setRightText(ACache.get(Utils.getApp()).getAsString(Constant.LOCATION));
        ilDate.setRightText(ACache.get(Utils.getApp()).getAsString(Constant.CREATE_TIME));

    }

    @OnClick({R.id.tv_cancel, R.id.tv_sure, R.id.btn_ying, R.id.btn_ruan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                bsGaoliang.setProgress(ziDingYiData.gaoliang);//高亮亮度
                bsJieneng.setProgress(ziDingYiData.jieneng);//节能亮度
                bsJianliang.setProgress(ziDingYiData.jianliang);//渐亮时长
                bsGaoliangChang.setProgress(ziDingYiData.gaoliangchang);//高亮时长
                bsJianan.setProgress(ziDingYiData.jianan);//渐暗时长
                break;
            case R.id.tv_sure:
                if (rbChangliang.isChecked()){
                    sendCommand(CommandUtil.getChangLiang(bsYuzhi.getProgress(),bsYanshi.getProgress(),bsChangliang.getProgress()));
                }else {
                    sendCommand(CommandUtil.getJieNeng(bsYuzhi.getProgress(),bsYanshi.getProgress(),isYingjian,bsJianliang.getProgress(),
                            bsGaoliangChang.getProgress(),bsJianan.getProgress(),bsGaoliang.getProgress(),bsJieneng.getProgress()));
                    ziDingYiData.setGaoliang(bsGaoliang.getProgress());
                    ziDingYiData.setJieneng(bsJieneng.getProgress());
                    ziDingYiData.setJianliang(bsJianliang.getProgress());
                    ziDingYiData.setGaoliangchang(bsGaoliangChang.getProgress());
                    ziDingYiData.setJianan(bsJianan.getProgress());
                }
                break;
            case R.id.btn_ying:
                btnYing.setTextColor(getResources().getColor(R.color.colorAccent));
                btnRuan.setTextColor(getResources().getColor(R.color.gray_2));
                ivJienengCover.setVisibility(View.VISIBLE);
                isYingjian=true;
                break;
            case R.id.btn_ruan:
                btnYing.setTextColor(getResources().getColor(R.color.gray_2));
                btnRuan.setTextColor(getResources().getColor(R.color.colorAccent));
                ivJienengCover.setVisibility(View.GONE);
                isYingjian=false;
                break;
        }
    }

    private void projectlist() {
        disposables.add(RetrofitHelper.getHelper(getActivity()).getUserInfoService().projectlist()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ProjectListInfo>() {
                    @Override
                    public void accept(ProjectListInfo info) {
                        if (info != null && !info.getData().isEmpty()) {
                            ACache.get(Utils.getApp()).put(Constant.ID, info.getData().get(0).getId() + "");
                            ACache.get(Utils.getApp()).put(Constant.ADDRESS, info.getData().get(0).getAddress());
                            ACache.get(Utils.getApp()).put(Constant.NAME, info.getData().get(0).getName());
                            devicelist();
                        } else {
                            ntTotal.setContentState(NetStateLayout.CONTENT_STATE_SHOW_NET_ERROR);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        throwable.printStackTrace();
                        ntTotal.setContentState(NetStateLayout.CONTENT_STATE_SHOW_NET_ERROR);
                    }
                })
        );
    }

    private void devicelist() {
        disposables.add(RetrofitHelper.getHelper(getActivity()).getUserInfoService().devicelist(ACache.get(Utils.getApp()).getAsString(Constant.ID))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DeviceListInfo>() {
                    @Override
                    public void accept(DeviceListInfo info) {
                        if (info != null && !info.getData().isEmpty()) {
                            ACache.get(Utils.getApp()).put(Constant.SN, info.getData().get(0).getSn());
                            ACache.get(Utils.getApp()).put(Constant.DEVICE_SN, info.getData().get(0).getDevicesn());
                            ACache.get(Utils.getApp()).put(Constant.LOCATION, info.getData().get(0).getLocation());
                            ACache.get(Utils.getApp()).put(Constant.CREATE_TIME, info.getData().get(0).getCreatetime());
                            lastLightData();
                        } else {
                            ntTotal.setContentState(NetStateLayout.CONTENT_STATE_SHOW_NET_ERROR);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        throwable.printStackTrace();
                        ntTotal.setContentState(NetStateLayout.CONTENT_STATE_SHOW_NET_ERROR);
                    }
                })
        );
    }

    private void lastLightData() {
        disposables.add(RetrofitHelper.getHelper(getActivity()).getUserInfoService().lastLightData(ACache.get(Utils.getApp()).getAsString(Constant.SN))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<LastLightDataInfo>() {
                    @Override
                    public void accept(LastLightDataInfo info) {
                        if (info != null && !info.getData().isEmpty()) {
                            ACache.get(Utils.getApp()).put(Constant.EQ, info.getData().get(0).getEq() + "");
                            ACache.get(Utils.getApp()).put(Constant.TIME, info.getData().get(0).getCreatetime());
                            ACache.get(Utils.getApp()).put(Constant.TEMP_SN,info.getData().get(0).getSn());
                            ntTotal.setContentState(NetStateLayout.CONTENT_STATE_HIDE);
                            bindData();
                        } else {
                            ntTotal.setContentState(NetStateLayout.CONTENT_STATE_SHOW_NET_ERROR);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        throwable.printStackTrace();
                        ntTotal.setContentState(NetStateLayout.CONTENT_STATE_SHOW_NET_ERROR);
                    }
                })
        );
    }

    private boolean background = true;

    private void background() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (background) {
                    lastLightData();
                    try {
                        Thread.sleep(1000 * 60);
//                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        background = false;
    }

    private void sendCommand(String command){
        mLoadingDialog.setLoadingText("发送指令中...").show();
        disposables.add(RetrofitHelper.getHelper(getActivity()).getUserInfoService().command(ACache.get(Utils.getApp()).getAsString(Constant.DEVICE_SN),command)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResult>() {
                    @Override
                    public void accept(BaseResult info) {
                       if ("success".equals(info.getMsg())){
                           Toast.makeText(getContext(),"发送成功",Toast.LENGTH_SHORT).show();
                       }else {
                           Toast.makeText(getContext(),"发送失败",Toast.LENGTH_SHORT).show();
                       }
                        mLoadingDialog.close();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        throwable.printStackTrace();
                        ntTotal.setContentState(NetStateLayout.CONTENT_STATE_SHOW_NET_ERROR);
                        mLoadingDialog.close();
                    }
                })
        );
    }

    public static  class  ZiDingYiData{
        int gaoliang=70;
        int jieneng=20;
        int jianliang=5;
        int gaoliangchang=20;
        int jianan=10;

        public ZiDingYiData() {
        }

        public ZiDingYiData(int gaoliang, int jieneng, int jianliang, int gaoliangchang, int jianan) {
            this.gaoliang = gaoliang;
            this.jieneng = jieneng;
            this.jianliang = jianliang;
            this.gaoliangchang = gaoliangchang;
            this.jianan = jianan;
        }

        public int getGaoliang() {
            return gaoliang;
        }

        public void setGaoliang(int gaoliang) {
            this.gaoliang = gaoliang;
        }

        public int getJieneng() {
            return jieneng;
        }

        public void setJieneng(int jieneng) {
            this.jieneng = jieneng;
        }

        public int getJianliang() {
            return jianliang;
        }

        public void setJianliang(int jianliang) {
            this.jianliang = jianliang;
        }

        public int getGaoliangchang() {
            return gaoliangchang;
        }

        public void setGaoliangchang(int gaoliangchang) {
            this.gaoliangchang = gaoliangchang;
        }

        public int getJianan() {
            return jianan;
        }

        public void setJianan(int jianan) {
            this.jianan = jianan;
        }
    }

}
